package UI;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class ClentReaderThread extends Thread{
    private Socket socket;
    private ChatRoomUI chatRoomUI;
    private DataInputStream dis;

    public ClentReaderThread(Socket socket,ChatRoomUI chatRoomUI)
    {
        this.socket = socket;
        this.chatRoomUI = chatRoomUI;
    }

    @Override
    public void run()
    {
        try {
            dis = new DataInputStream(socket.getInputStream());
            //接受服务端发送的消息1.更新人数的消息，2.群发的消息，3.私聊的消息
            while(true){
                int type = dis.readInt();
                switch (type) {
                    case ConstantClient.UPDATE_USERLIST:
                        //更新用户列表
                        updateUserList();
                        break;
                    case ConstantClient.GROUP_MESSAGE:
                        //群发消息
                        gotoshowmsg();
                        break;
                    case ConstantClient.PRIVATE_MESSAGE:
                        //私聊消息
                        gotoshowPrivatemsg();
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void gotoshowPrivatemsg() throws Exception {
        String msg = dis.readUTF();
        chatRoomUI.showPrivateMsg(msg);
    }

    private void gotoshowmsg() throws Exception {
        String msg = dis.readUTF();
        chatRoomUI.showMsg(msg);
    }

    private void updateUserList() throws Exception {
        int count = dis.readInt();
        String[] users = new String[count];
        for (int i = 0; i < count; i++) {
            users[i] = dis.readUTF();
        }
        chatRoomUI.updateUserList(users);
    }
}
